package com.hinner.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hinner.entity.User;
import com.hinner.entity.vo.ModifyPasswordVO;
import com.hinner.entity.vo.QueryUserVO;
import com.hinner.entity.vo.UserVO;
import com.hinner.exception.CustomException;
import com.hinner.mapper.CompanyMapper;
import com.hinner.mapper.UserMapper;
import com.hinner.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String whoSend;


    @Override
    public User modify(UserVO userVO) {
        if (ObjectUtil.isEmpty(userVO.getId())){
            return null;
        }
        User user = userMapper.selectById(userVO.getId());
        return null;
    }

    /**
     * 注册新用户: 不能重复
     * @param userVO
     */
    @Override
    public void register(UserVO userVO) {
        if (StringUtils.isEmpty(userVO.getUsername()) || StringUtils.isEmpty(userVO.getPassword())){
            throw new CustomException("用户名和密码不能为空");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,userVO.getUsername());
        User newUser = userMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(newUser)){
            log.error("=============>" +"该用户名已存在,请重新注册");
            throw new CustomException("该用户名已存在,请重新注册");
        }
        // 如果数据库中没有任何一条数据，那么第一个注册的用户就是管理员
        if (CollectionUtils.isEmpty(this.list())){
            userVO.setRole("ROLE_ADMIN");
        }else {
            // 默认注册时是普通用户
            userVO.setRole("ROLE_USER");
        }

        userVO.setIsActived(0);
        userVO.setAvator("avatar.gif");
        userMapper.insert(userVO);

    }


    /**
     * 用户登录
     * @param userVO
     * @return
     */
    @Override
    public User login(UserVO userVO) {
        if (StringUtils.isEmpty(userVO.getUsername()) || StringUtils.isEmpty(userVO.getPassword())){
            throw new CustomException("用户名不能为空!");
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,userVO.getUsername())
                .eq(User::getPassword,userVO.getPassword());
        User user = userMapper.selectOne(wrapper);
        user.setCompanyName(companyMapper.selectById(user.getCompanyId()).getCompanyName()); // 这字段不会入库的
        if (ObjectUtil.isEmpty(user)){
            throw new CustomException("用户名或密码错误，请重试!");
        }

        if (1 == user.getIsDeleted()){
            throw new CustomException("该账号已被删除,请联系管理员");
        }

        if (1 == user.getIsActived()){
            throw new CustomException("该账号已被冻结,请联系管理员");
        }

        user.setLastLoginTime(new Date());
        userMapper.updateById(user);
        return user;
    }

    @Override
    public boolean forgotPassword(String username, String email) {
        User user = this.findByUserNameAndEmail(username, email);
        if (ObjectUtil.isNull(user)){
            return false;
        }

        String newPassword = this.generateRandomPassword();
        user.setPassword(newPassword);
        this.updateById(user);
        sendEmail(user.getEmail(), "密码重置", "您的新密码是: " + newPassword);
        return true;
    }

    @Override
    public User findByUserNameAndEmail(String username, String email) {
        return this.getOne(new QueryWrapper<User>().eq("username",username)
                .eq("email", email));
    }

    @Override
    public PageInfo<User> findAllUsers(QueryUserVO query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<User> users = this.list(new LambdaQueryWrapper<User>().like(StringUtils.isNotEmpty(query.getUsername()), User::getUsername, query.getUsername()));
        System.out.println("users = " + users);
        return new PageInfo<>(users);
    }

    @Override
    public String updateStatus(Integer userId, Integer isActived) {
        System.out.println("userId = " + userId);
        boolean update = this.update(new UpdateWrapper<User>().set("isActived", isActived).eq("id", userId));
        return update ? "更新成功" : "更新失败";
    }

    /**
     * 我这个根据id查询的，所以该用户肯定是存在的
     * @param vo
     * @return
     */
    @Override
    public Boolean modifyPassword(ModifyPasswordVO vo) {
        User queryUser = this.getOne(new QueryWrapper<User>().eq("id", vo.getId()).eq("password", vo.getOldPassword()));
        if (queryUser == null){
            log.error("=============>" +"原密码错误");
            return false;
        }


        // 检查原密码是否正确
//        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        if (!passwordEncoder.matches(vo.getOldPassword(), queryUser.getPassword())) {
//            throw new CustomException("原密码错误");
//        }
//
//        // 设置新密码并加密
//        String encryptedPassword = passwordEncoder.encode(vo.getNewPassword());
//        queryUser.setPassword(encryptedPassword);

        queryUser.setPassword(vo.getNewPassword());
        return this.updateById(queryUser);
    }


    /**
     * 生成随机 8 位密码
     *
     * @return 随机密码
     */
    private String generateRandomPassword() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            password.append(characters.charAt(random.nextInt(characters.length())));
        }
        return password.toString();
    }


    /**
     * 发送邮件
     *
     * @param to      收件人邮箱
     * @param subject 邮件主题
     * @param text    邮件内容
     */
    private void sendEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(whoSend);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    }
}
